package ca.etsmtl.log430.lab3;

import java.io.PipedReader;
import java.io.PipedWriter;

public class TauxFilter extends Thread {
	boolean done;
	PipedReader inputPipe = new PipedReader();
	PipedWriter outputPipe = new PipedWriter();
	TauxCondition _condition;
	int _taux = 0;
	public TauxFilter(PipedWriter inputPipe,
			PipedWriter outputPipe,TauxCondition condition, int taux) {

	
		try {

			// Connect inputPipe
			this.inputPipe.connect(inputPipe);

			// Connect outputPipe
			this.outputPipe = outputPipe;
			this._condition = condition;
			this._taux = taux;

		} catch (Exception Error) {

		} // try/catch

	} // Constructor
	
	// This is the method that is called when the thread is started
	public void run() {

		// Declarations

		char[] characterValue = new char[1];
		String[] champs = new String[7];
		// char array is required to turn char into a string
		String champ = "";
		int i = 0;
		// string is required to look for the keyword
		int integerCharacter; // the integer value read from the pipe

		try {

			done = false;

			while (!done) {

				integerCharacter = inputPipe.read();
				characterValue[0] = (char) integerCharacter;

				if (integerCharacter == -1) { // pipe is closed

					done = true;

				} else {

					if (integerCharacter == '\n') { // end of line
						
						champs[i] = champ;
						Projet p = new Projet(champs[0],champs[1],champs[2],champs[3],champs[4],champs[5],champs[6]);
						String lineOfText = "";
						if (respectCondition(p)) {
							lineOfText = p.toString();
							outputPipe.write(lineOfText, 0, lineOfText.length());
							outputPipe.flush();
						}
						i=0;
						champ = "";

					} 
					else if(integerCharacter == ' ' && i < 6)
					{
							champs[i] = champ;
							i++;
							champ = "";
					}
					else {

						champ += new String(characterValue);

					} // if //

				} // if

			} // while

		} catch (Exception error) {

		} // try/catch
		
		try {

			inputPipe.close();

			outputPipe.close();

		} catch (Exception error) {


		} // try/catch

	} // run

	private boolean respectCondition(Projet projet) {
		switch (_condition) {
		case equal:
			return Integer.parseInt(projet._taux.trim()) == this._taux;
		case greater:
			return Integer.parseInt(projet._taux.trim()) > this._taux;
		case smaller:
			return Integer.parseInt(projet._taux.trim()) < this._taux;
		}
		return false;
	}
}
